/*
 * Bitcoin-JSON-RPC-Client License
 * 
 * Copyright (c) 2013, Mikhail Yevchenko.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 
 * Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject
 * to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
 * THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package com.spark.blockchain.rpcclient;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author Mikhail Yevchenko <m.ṥῥẚɱ.ѓѐḿởύḙ@azazar.com>
 */
public class BitcoinUtil {

    public static double normalizeAmount(double amount) {
        return (long) (0.5d + (amount / 0.00000001)) * 0.00000001;
    }

    public static String sendTransaction(Bitcoin bitcoin, String targetAddress, Double amount, Double txFee) throws BitcoinException {
        List<Bitcoin.Unspent> unspents = bitcoin.listUnspent(3);
        amount = normalizeAmount(amount);
        txFee = normalizeAmount(txFee);
        double moneySpent = 0.00;
        double moneyChange = 0.00;
        if (unspents.size() == 0) {
            throw new BitcoinException("insufficient coin");
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String account = "acct-change-" + df.format(new Date());

        String changeAddress = bitcoin.getAccountAddress(account);
        if(changeAddress == null ){
            changeAddress = bitcoin.getNewAddress(account);
        }
        System.out.println("change address:"+changeAddress);
        BitcoinRawTxBuilder builder = new BitcoinRawTxBuilder(bitcoin);
        for (Bitcoin.Unspent unspent : unspents) {
            double amt = normalizeAmount(unspent.amount().doubleValue());
            moneySpent += amt;
            builder.in(new Bitcoin.BasicTxInput(unspent.txid(), unspent.vout()));
            //取出未花费的交易，直到能够支付
            if (moneySpent >= (amount + txFee)) {
                break;
            }
        }
        if(moneySpent < amount + txFee){
            throw new BitcoinException("insufficient coin");
        }
        moneyChange = normalizeAmount(moneySpent - amount - txFee);
        System.out.println("moneyChange:"+moneyChange);
        builder.out(targetAddress, new BigDecimal(amount));
        if (moneyChange > 0) {
            //设置找零
            builder.out(changeAddress, new BigDecimal(moneyChange));
        }
        return builder.send();

    }
}
